package org.jiulou.util.controller;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.jiulou.util.BeanUtil;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

public class ControllerUtil {
	
	/**
	 * 把校验框架返回的错误代码转成消息，支持国际化<br>
	 * @param result
	 * @param locale
	 * @return 字段名:错误消息<br>
	 * 比如 key="username",value="用户名不能为空"
	 */
	public static Map<String,String> translateValidatorMsgs(BindingResult result,Locale locale){
		
		MessageSource messageSource = BeanUtil.getBean("messageSource");
		
		Map<String,String> validatorMsgs = new HashMap<String,String>();
		for (FieldError fieldError : result.getFieldErrors()) {
	        validatorMsgs.put(fieldError.getField()
	        		,messageSource.getMessage(fieldError.getCode()
	        				, fieldError.getArguments(), fieldError.getDefaultMessage()
	        				, locale));
		    
		}
		
		return validatorMsgs;
	}
	
	/**
	 * 把全局错误代码转成消息，支持国际化
	 * @param result
	 * @param locale
	 * @return 错误代码:错误消息<br>
	 * 比如 key="login.error.password",value="用户名或者密码不正确"
	 */
	public static Map<String,String> translateGlobleMsgs(BindingResult result,Locale locale){
		
		MessageSource messageSource = BeanUtil.getBean("messageSource");
		
		Map<String,String> validatorMsgs = new HashMap<String,String>();
		for (ObjectError objectError : result.getGlobalErrors()) {
	        validatorMsgs.put(objectError.getCode()
	        		,messageSource.getMessage(objectError.getCode()
	        				, objectError.getArguments(), objectError.getDefaultMessage()
	        				, locale));
		}
		
		return validatorMsgs;
	}
}
